package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.TaskFacilitiesRelationLogic;
import cn.topevery.garden.dal.logic.TaskInfoLogic;
import cn.topevery.garden.entity.dto.TaskInfoDTO;
import cn.topevery.garden.entity.po.TaskFacilitiesRelation;
import cn.topevery.garden.entity.po.TaskInfo;
import cn.topevery.garden.entity.query.TaskInfoQuery;
import cn.topevery.garden.entity.vo.TaskInfoVO;
import com.github.dozermapper.core.Mapper;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.entity.KeyValue;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务信息
 *
 * @author code-generate
 * @date 2021-08-26
 */
@Api(tags = "任务信息")
@RestController
@RequestMapping("/task")
public class TaskInfoController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    TaskInfoLogic taskInfoLogic;

    @Autowired
    TaskFacilitiesRelationLogic taskFacilitiesRelationLogic;

    /**
     * 获取任务信息分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取任务信息页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<TaskInfoVO>> listPage(@RequestBody TaskInfoQuery query) {
        return JsonResult.ok(taskInfoLogic.listPage(query));
    }

    @ApiOperation("通过公园Id获取公园详情")
    @GetMapping("/getInfoById")
    public JsonResult<TaskInfoVO> getInfoById(@RequestParam Integer id) {
        TaskInfo entity = taskInfoLogic.getEntity(id);
        TaskInfoVO vo= mapper.map(entity, TaskInfoVO.class);
        DbCsp query = new DbCsp();
        query.whereMap.add(new KeyValue<>("taskId", id));
        List<TaskFacilitiesRelation> sectionParkRelationList = taskFacilitiesRelationLogic.getSearch(query);
        vo.setFacilitiesList(new ArrayList<>());
        sectionParkRelationList.forEach(f -> {
            Map<String,Object> mapObj=new HashMap<>();
            mapObj.put("id",f.facilitiesId);
            mapObj.put("label",f.facilitiesName);
            vo.getFacilitiesList().add(mapObj);
        });
        return JsonResult.ok(vo);
    }

    @ApiOperation("新增/编辑 任务信息信息")
    @PostMapping("/save")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody TaskInfoDTO dto) {
        TaskInfo taskInfo=mapper.map(dto, TaskInfo.class);
        taskInfoLogic.saveOrUpdate(getUser().id.toString(),taskInfo);
        DbCsp query = new DbCsp();
        query.whereMap.add(new KeyValue<>("taskId",taskInfo.id));
        List<TaskFacilitiesRelation> taskFacilitiesRelationList = taskFacilitiesRelationLogic.getSearch(query);
        try {
            for (Map<String, Object> mapObj :
                    dto.getFacilitiesList()) {
                Integer facilitiesId = (int) mapObj.get("id");
                String facilitiesName = mapObj.get("label").toString();
                //存在不执行操作
                List<TaskFacilitiesRelation> addObj = taskFacilitiesRelationList.stream().filter(f -> f.getFacilitiesId().equals(facilitiesId)).collect(Collectors.toList());
                if (addObj.size() == 0) {
                    TaskFacilitiesRelation entity = new TaskFacilitiesRelation();
                    entity.status = 1;
                    entity.beginDate = LocalDateTime.now();
                    entity.taskId = taskInfo.getId();
                    entity.facilitiesId = facilitiesId;
                    entity.facilitiesName = facilitiesName;
                    taskFacilitiesRelationLogic.insert(getUser().id.toString(), entity);
                } else {
                    taskFacilitiesRelationList.removeAll(addObj);
                }
            }
            //删除剩余元素
            for (TaskFacilitiesRelation entity :
                    taskFacilitiesRelationList) {
                entity.status = 2;
                entity.endDate = LocalDateTime.now();
                taskFacilitiesRelationLogic.update(getUser().id.toString(), entity);
                taskFacilitiesRelationLogic.delete(getUser().id.toString(), Arrays.asList(entity.id));
            }
        }
        catch (Exception ex){
           return JsonResult.error("提交的数据有误!",false);
        }
        return JsonResult.ok(true);
    }

    @ApiOperation("根据自增ID批量删除")
    @PostMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestBody Integer[] ids) {
        taskInfoLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出任务信息信息")
    @GetMapping("/export")
    public void export(TaskInfoQuery query, HttpServletResponse response) {
        List<TaskInfoVO> list = taskInfoLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "任务信息", "sheet1", TaskInfoVO.class, "任务信息", response);
    }

}
